package main

import (
	"alertmanagerWebhook/core"
	"alertmanagerWebhook/global"
	"alertmanagerWebhook/routers"
	"context"
	"errors"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func main() {
	// Initialize configuration from YAML file
	core.InitYaml()

	// Set up logging
	logFilePath := global.Config.System.LogFilePath
	var closeLogger func() // 声明一个关闭函数
	global.Logger, closeLogger = setupLogrus(logFilePath)
	defer closeLogger() // 确保关闭日志文件

	// Set Gin global.Logger to use logrus as the global.Logger
	gin.SetMode(gin.ReleaseMode) // Set Gin mode to release, adjust if needed
	gin.DefaultWriter = global.Logger.Writer()
	gin.DefaultErrorWriter = global.Logger.Writer()

	// Initialize router
	router := routers.InitRouterGroup()
	srv := &http.Server{
		Addr:    global.Config.System.Addr(),
		Handler: router,
	}

	// Start the server in a goroutine
	go func() {
		global.Logger.Info("Starting server...")
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			global.Logger.Fatalf("Listen: %s\n", err)
		}
	}()

	// Gracefully handle shutdown signals
	handleShutdown(srv)
}

// setupLogrus initializes logrus and returns a global.Logger.
func setupLogrus(path string) (*logrus.Logger, func()) {
	Logger := logrus.New()
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		logrus.Fatalf("Error opening log file: %v", err)
	}
	Logger.Out = f
	Logger.SetFormatter(&logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	Logger.SetReportCaller(true)

	return Logger, func() { f.Close() } // 返回一个关闭函数
}

func handleShutdown(srv *http.Server) {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	global.Logger.Info("Shutting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		global.Logger.Fatal("Server forced to shutdown:", err)
	}

	global.Logger.Info("Server exiting")
}
